#include <cstdlib>
#include <chrono>

#include <fmt/format.h>

#include "ssd_1306_128_64.hpp"
#include "gfx_utility.hpp"

#include <opencv2/videoio.hpp>
#include <opencv2/imgcodecs.hpp>
#include <iostream>

void playVideo(const std::string &path, GFX_Utility &gfx) {
    using namespace cv;
    VideoCapture cap(path);
    if (cap.isOpened()) {
        Mat frame;
        std::chrono::steady_clock::time_point last{};
        while(cap.read(frame))
        {
            imwrite("frame.png", frame);
            gfx.reset().drawImage("frame.png", {0,0,128,64}).commit();
            auto now = std::chrono::steady_clock::now();
            auto t = std::chrono::duration_cast<std::chrono::milliseconds>(now - last).count();
            std::cout << cap.get(cv::CAP_PROP_POS_FRAMES) << ' ' << t << "ms" << std::endl;
            last = now;
            cap.read(frame); // skip 1 frame
//            cap.read(frame);
        }
    } else {
        abort();
    }
}

int main() {
    using namespace std;

    GFX_Utility::loadFont("SourceHanSansSC.otf", 0);

    auto r = gpioInitialise();
    if (r != gpioVersion())
        abort();

    SSD1306_128_64 oled(IIC(23, 24, 0x3c));
    oled.init();
    oled.clear();
    oled.fill();
    oled.display();

    time_sleep(0.1);

    GFX_Utility screen(&oled);

//    int i = 1000;
//    std::chrono::steady_clock::time_point last{};
//    while (--i) {
//        auto now = chrono::steady_clock::now();
//        auto t = chrono::duration_cast<std::chrono::milliseconds>(now - last).count();
//        screen.reset()
//                .fontSize(12)
//                .drawRect({0, 0, 128, 64})
//                .drawText(fmt::format("{:.2f} FPS", 1000.0 / t), {0, 0, 128, 14}, Left)
//                .commit();
//        last = now;
//    }
    playVideo("badapple.mp4", screen);

    gpioTerminate();
}
